package com.recorder.recorder_lib.core;

import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.util.Log;

import com.recorder.recorder_lib.utils.FileManager;

import java.io.File;
import java.io.IOException;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * desc   : 录音服务
 * time   : 2018年12月21日15 : 39
 */
public class RecordingService extends Service {
    private static final String LOG_TAG = "RecordingService";
    private RecordingBinder mBinder = new RecordingBinder();
    private OnRecordingListener mOnRecordingListener;
    private ScheduledExecutorService mThreadPool;//定时器线程池
    private MediaRecorder mMediaRecorder = null;
    private long startTime;
    private String filePath;
    final TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if (mOnRecordingListener != null) {
                mOnRecordingListener.onProgress(System.currentTimeMillis() - startTime);
            }
        }
    };

    public class RecordingBinder extends Binder {
        public RecordingService getService() {
            return RecordingService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        mThreadPool = Executors.newScheduledThreadPool(1);
        mThreadPool.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS);
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startTime = System.currentTimeMillis();
        startRecordingSound();
    }

    @Override
    public void onDestroy() {
        if (mOnRecordingListener != null) mOnRecordingListener.onEnd();
        stopRecord();
        mThreadPool.shutdown();
        mMediaRecorder = null;
        super.onDestroy();
    }

    private void startRecordingSound() {
        filePath = FileManager.createFilePath(startTime);
        if (mMediaRecorder == null)
            mMediaRecorder = new MediaRecorder();
        try {
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            mMediaRecorder.setOutputFile(filePath);
            mMediaRecorder.prepare();
            mMediaRecorder.start();
            if (mOnRecordingListener != null) mOnRecordingListener.onStart();
        } catch (IllegalStateException | IOException e) {
            Log.e(LOG_TAG, "call startAmr(File mRecAudioFile) failed!" + e.getMessage());
        }
        Log.e(LOG_TAG, "time:" + startTime + ",filePath:" + filePath);
    }

    public void stopRecord() {
        Log.e(LOG_TAG, "stop");
        try {
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
            filePath = "";
        } catch (RuntimeException e) {
            Log.e(getClass().getName(), e.toString());
//            mMediaRecorder.reset();
//            mMediaRecorder.release();
//            mMediaRecorder = null;
//            File file = new File(filePath);
//            if (file.exists()) file.delete();
//            filePath = "";
        }
    }

    public void setOnRecordingListener(@NonNull OnRecordingListener mOnRecordingListener) {
        this.mOnRecordingListener = mOnRecordingListener;
    }
}